package controllers;

import java.util.concurrent.atomic.AtomicBoolean;

import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.WebSocket;

public class MyWebSocket {

	public static WebSocket<String> index() {
		System.out.println("?");
		final AtomicBoolean kill = new AtomicBoolean();
		return new WebSocket<String>() {
			long startTime=System.currentTimeMillis();
			float pings=0;
			// Called when the Websocket Handshake is done.
			public void onReady(WebSocket.In<String> in,
					final WebSocket.Out<String> out) {
					out.write("1");

				// For each event received on the socket,
				in.onMessage(new Callback<String>() {
					public void invoke(String event) {
						pings++;
						try{
							//Thread.sleep(100);
						}
						catch(Exception e){}
						if(System.currentTimeMillis()-startTime>10000){
							long now=System.currentTimeMillis();
							long delta=now-startTime;
							float deltaF=(float)delta/1000f;
							System.out.println(pings/deltaF);
							pings=0;
							startTime=now;
						}
						Integer val=Integer.parseInt(event);
						//val=val+1;
						out.write(val.toString());
					}
				});

				// When the socket is closed.
				in.onClose(new Callback0() {
					public void invoke() {
						kill.set(false);
						System.out.println("Disconnected");

					}
				});

				// Send a single 'Hello!' message
				//out.write("Hello!");
				//startThread(out, kill);
			}

		};
	}

	private static void startThread(final WebSocket.Out<String> out,
			final AtomicBoolean kill) {
		Runnable runnable = new Runnable() {
			public void run() {
				int count = 0;
				while (kill.get()) {
					try {
						Thread.sleep(10);
						out.write(String.valueOf(count++));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		new Thread(runnable).start();
	}
}